package com.louis.iread.utils;

import android.icu.util.RangeValueIterator;
import android.util.Log;

import com.louis.iread.bean.ContentItem;
import com.louis.iread.bean.SearchResultItem;
import com.louis.iread.bean.Website;
import com.louis.iread.net.HttpUtil;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.SocketException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by louis on 17-3-21.
 */

public class NovelUtil {

    //搜索小说
    public static ArrayList<SearchResultItem> searchNovel(String novelName, Website website) throws IOException{
        if (novelName == null || website == null) {
            return null;
        }
        String url = website.getSearch().replace("{novel}", URLEncoder.encode(novelName, website.getSkEncoding()));
        String html = HttpUtil.getStringFromUrl(url, website.getUserAgent(), website.getHost(), null);

        if (html == null || html.length() == 0) {
            return null;
        }

        Document document = Jsoup.parse(html, website.getHost());
        if (document == null) {
            return null;
        }

        ArrayList<SearchResultItem> list = new ArrayList<>();

        Elements items = document.select(website.getSearchList());
//        Log.d("novel", items.toString());
        for (Element item : items) {
            SearchResultItem resultItem = new SearchResultItem();
            resultItem.setWebsite(website);
            resultItem.setSiteName(website.getSiteName());
//            resultItem.setNovelUrl(item.select(website.getSearchNovelUrl()).attr("href").trim());
            if (!"".equals(website.getSearchCover())) {
                resultItem.setCover(item.select(website.getSearchCover()).first().attr("src").trim());
            } else {
                resultItem.setCover("");
            }

            String novelUrl = item.select(website.getSearchNovelUrl()).attr("abs:href").trim();
            if (novelUrl == null || novelUrl.length() == 0) {
                continue;
            }

            //从小说url提取type id 和novel id
            String typeIdCss = website.getTypeId();
            if (typeIdCss != null && !typeIdCss.trim().isEmpty()) {
                Pattern pattern = Pattern.compile(website.getTypeId());
                Matcher matcher = pattern.matcher(novelUrl);
                if (!matcher.find()) {
                    continue;
                }
                resultItem.setTypeId(matcher.group(1));
            } else {
                resultItem.setTypeId("");
            }

            String novelIdCss = website.getNovelId();
            if (novelIdCss != null && !novelIdCss.trim().isEmpty()) {
                Pattern pattern = Pattern.compile(website.getNovelId());
                Matcher matcher = pattern.matcher(novelUrl);
                if (!matcher.find()) {
                    continue;
                }
                resultItem.setNovelId(matcher.group(1));
            } else {
                continue;
            }

            resultItem.setNovelTitle(item.select(website.getSearchNovelName()).first().text().trim());
            resultItem.setNovelAuthor(item.select(website.getSearchNovelAuthor()).text().replace("小说", "")
                    .replace("作者", "").replace("：", "").replace(":", "").trim());
            resultItem.setNovelType(item.select(website.getSearchNovelType()).text().replace("类型", "")
                    .replace("：", "").replace(":", "").replace("[", "").replace("]", "").trim());
            if (!"".equals(website.getUpdateTime())) {
                Element updateTime = item.select(website.getUpdateTime()).first();
                if (updateTime != null) {
                    String updateTimeStr = updateTime.text().trim();
                    if (updateTimeStr != null && !"".equals(updateTimeStr)) {
                        if (!updateTimeStr.startsWith("20")) {
                            resultItem.setNovelUpdateTime("20"+updateTimeStr);
                        } else {
                            resultItem.setNovelUpdateTime(updateTimeStr);
                        }
                    }
                }
            }
            if (!"".equals(website.getLatestArticle())) {
                Element latestElement = item.select(website.getLatestArticle()).first();
                if (latestElement != null) {
                    String latestArticleStr = latestElement.text().trim();
                    if (latestArticleStr != null && !"".equals(latestArticleStr)) {
                        resultItem.setNovelLatestArticle(latestArticleStr);
                    }
                }
            }
//            resultItem.setNovelLatestArticle(item.select(website.getSearchNovelLatestArticle()).text().trim());
//            resultItem.setNovelDesc(item.select(website.getSearchNovelDesc()).text().trim());
            resultItem.setSimilarValue(novelName, item.select(website.getSearchNovelName()).first().text());
            list.add(resultItem);
        }

        return list;
    }

    /*
    解析小说目录
     */
    public static List<ContentItem> parseContents(Document document, Website website) {
        if (document == null || website == null) {
            return null;
        }
        List<ContentItem> contents = new ArrayList<>();
        Elements contentsList = document.select(website.getContents());
        for (Element item : contentsList) {
            ContentItem contentItem = new ContentItem();
            contentItem.setWebsite(website);
            contentItem.setContentTitle(item.text());
            contentItem.setUrl(item.absUrl("href"));
            contents.add(contentItem);
//            Log.i(contentItem.getContentTitle(), contentItem.getUrl());
        }
        return contents;
    }

    /*
    解析小说目录成hash表
     */
    public static HashMap<String, ContentItem> parseContentsToHashMap(Document document, Website website) {
        if (document == null || website == null) {
            return null;
        }
        HashMap<String, ContentItem> map = new HashMap<>();
        Elements contentsList = document.select(website.getContents());
        for (Element item : contentsList) {
            ContentItem contentItem = new ContentItem();
            contentItem.setWebsite(website);
            contentItem.setContentTitle(item.text());
            contentItem.setUrl(item.absUrl("abs:href"));
            map.put(contentItem.getUrl(), contentItem);
        }
        return map;
    }

    static Pattern pattern = Pattern.compile("[\\s]{1,8}");
    /*
    获取小说章节内容
     */
    public static String getArticleContent(String url, Website website) {
        if (url == null || website == null) {
            return null;
        }
        try {
            String html = HttpUtil.getStringFromUrl(url, website.getUserAgent(), website.getHost(), null);
            if (html == null) {
                return null;
            }
            Document document = Jsoup.parse(html);
            if (document == null) {
                return null;
            }

            Elements elements = document.select(website.getArticleContent());
            if (elements == null) {
                return null;
            }
            Element element = elements.first();
            if (element == null) {
                return null;
            }
            String content = element.text();
            if (content == null) {
                return null;
            }
            Matcher matcher = pattern.matcher(content);
            return matcher.replaceAll("\n        ");
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /*** 半角转换为全角
     *
     * @param input
     * @return
     */
    public static String ToDBC(String input) {
        char[] c = input.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] == 12288) {
                c[i] = (char) 32;
                continue;
            }
            if (c[i] > 65280 && c[i] < 65375)
                c[i] = (char) (c[i] - 65248);
        }
        return new String(c);
    }
}
